<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2017/12/23
 * Time: 20:07
 */

namespace controller;


use extend\wechat\pay\lib\JsApiPay;
use extend\wechat\pay\lib\PayNotifyCallBack;
use extend\wechat\pay\lib\WxPayApi;
use extend\wechat\pay\lib\WxPayConfig;
use extend\wechat\pay\lib\WxPayUnifiedOrder;
use model\Egg;
use model\Order;
use ulphp\Controller;

class Pay extends Controller
{
    /**
     * @param  int $id id
     * @return string
     */
    public function index($id)
    {
        $order     = new Order();
        $orderData = $order->row(['id' => $id, 'state' => 1]);
        if (empty($orderData)) {
            return json(['state' => false, 'msg' => '订单错误']);
        }

        $tools  = new JsApiPay();
        $openId = $orderData['openid'];
        $input  = new WxPayUnifiedOrder();
        $input->SetBody("碎片网络-购买金蛋");
        $input->SetAttach("碎片网络");
        $input->SetOut_trade_no($orderData['tid']);
        $input->SetTotal_fee($orderData['fee'] * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url(url('Pay/notify'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $editAddress     = $tools->GetEditAddressParameters();

        $this->assign('title', '碎片网络-购买金蛋');
        $this->assign('fee', $orderData['fee']);
        $this->assign('num', $orderData['num']);
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('editAddress', $editAddress);
        $this->fetch();
    }

    public function notify()
    {
        $notify          = new PayNotifyCallBack();
        $notify->callFun = function ($data) {
            if ($data['result_code'] == 'SUCCESS') {
                $order  = new Order();
                $result = $order->update(
                    [
                        'state' => 2
                    ], [
                        'tid'   => $data['out_trade_no'],
                        'state' => 1
                    ]
                );
                if ($result) {
                    $orderData = $order->row(['tid' => $data['out_trade_no']]);
                    $egg       = new Egg();
                    $result    = $egg->updateNum($orderData['num'], $orderData['openid'], $orderData['action_id']);
                    if (!$result) {
                        $egg->insert([
                            'action_id' => $orderData['action_id'],
                            'openid'    => $orderData['openid'],
                            'num'       => $orderData['num'],
                            'created'   => now()
                        ]);
                    }
                }

            }
        };
        $notify->Handle(false);
    }
}